public class demo1 {
    //降序解法
    int[]temp;
    public int reversePairs1(int[] nums) {
        temp=new int[nums.length];//注意提前定义
        return gbin(nums,0,nums.length-1);
    }
    public int gbi1(int[]nums,int left,int right){
        if(left>=right)return 0;
        int sum=0;
        int mid=(left+right)/2;
        //统计左右数组符合条件的
        sum+=gbi1(nums,left,mid);
        sum+=gbi1(nums,mid+1,right);
        int cur1=left,cur2=mid+1;
        //降序,统计一左一右符合条件的
        while(cur1<=mid){
            while(cur2<=right&&nums[cur2]>=nums[cur1]/2.0)cur2++;
            if(cur2>right)break;
            sum+=right-cur2+1;
            cur1++;
        }
        cur1=left;cur2=mid+1; int x=left;
        while(cur1<=mid&&cur2<=right){
            temp[x++]=nums[cur1]>=nums[cur2] ? nums[cur1++] : nums[cur2++];
        }
        while(cur1<=mid)temp[x++]=nums[cur1++];
        while(cur2<=right)temp[x++]=nums[cur2++];
        for(int i=left;i<=right;i++){
            nums[i]=temp[i];
        }
        return sum;
    }
    int[]temp1;
    public int reversePairs(int[] nums) {
        temp1=new int[nums.length];//注意提前定义
        return gbin(nums,0,nums.length-1);
    }
    public int gbin(int[]nums,int left,int right){
        if(left>=right)return 0;
        int sum=0;
        int mid=(left+right)/2;
        //统计左右数组符合条件的
        sum+=gbin(nums,left,mid);
        sum+=gbin(nums,mid+1,right);
        int cur1=left,cur2=mid+1;
        //降序,统计一左一右符合条件的
        while(cur2<=right){
            while(cur1<=mid&nums[cur2]>=nums[cur1]/2.0)cur1++;
            if(cur1>mid)break;
            sum+=mid-cur1+1;
            cur2++;
        }
        cur1=left;cur2=mid+1; int x=left;
        while(cur1<=mid&&cur2<=right){
            temp1[x++]=nums[cur1]>=nums[cur2] ? nums[cur2++] : nums[cur1++];
        }
        while(cur1<=mid)temp1[x++]=nums[cur1++];
        while(cur2<=right)temp1[x++]=nums[cur2++];
        for(int i=left;i<=right;i++){
            nums[i]=temp1[i];
        }
        return sum;
    }
}
